//
//  AccountDetailIndexViewController.m
//  ELife
//
//  Created by  刘奇男 on 11-5-17.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "AccountDetailIndexViewController.h"
#import "Constants.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "M13UserDefaults.h"
#import "GetMyData.h"
#import "LoginController.h"
#import "AlertView.h"

@implementation AccountDetailIndexViewController

@synthesize textFields, keys, tableView, detailModels;

int lineHeight = 25;
int y = 20;

- (void)initView
{
    keys = [[NSArray alloc] initWithObjects:@"可用余额",@"代金券",@"您的积分", nil];
    
    textFields =  [[NSMutableArray alloc] init];
    
    for (NSString *key in keys)
	{
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, y, 80, 20)];
        [label setBackgroundColor:[UIColor clearColor]];
        [label setTextColor:[UIColor whiteColor]];
        [label setText:key];
        [label setFont:[UIFont systemFontOfSize:[UIFont labelFontSize]]];
        [self.view addSubview:label];
        [label release];
        
        
        UITextField* textField = [[UITextField alloc] initWithFrame:CGRectMake(110, y, 180, 20)];
        [textField setUserInteractionEnabled:NO];
//        [textField setText:@"10"];
        [textField setTextColor:[UIColor darkGrayColor]];
        [textField setTextAlignment:UITextAlignmentCenter];
        [textField setBackgroundColor:[UIColor grayColor]];
        
        [textFields addObject:textField];
        [self.view addSubview:textField];
        [textField release];
        
        y += lineHeight;
    }
    
    y += 5;
    UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(10, y, 180, 20)];
    [l setBackgroundColor:[UIColor clearColor]];
    [l setTextColor:[UIColor whiteColor]];
    [l setText:@"最近纪录"];
    [l setFont:[UIFont systemFontOfSize:18]];
    [self.view addSubview:l];
    [l release];
    
    y += 25;
}

- (void) initTable
{
    
    tableView = [[UITableView alloc] initWithFrame:CGRectMake(10, y, 300, 200)];
    [tableView setBackgroundColor:[UIColor clearColor]];
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    
    
    [tableView setDataSource:self];
    [self.view addSubview:tableView];
    [tableView reloadData];
}

- (void)search
{
    NSString* userid = [GetMyData getUserId];
    if (userid == nil)
    {
        
        LoginController* lc = [[LoginController alloc] init:self];
        [self.navigationController pushViewController:lc animated:YES];
        [lc release];
        return;
        
    }
    
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"user.php"]];
    
    
    NSArray* info = [M13UserDefaults getUserDefaultsArray:USERINFO_NAMEANDPASSWORD];
    NSLog(@"UserInfo:---%@\n",info);
    
    NSString* userName = [GetMyData getUserId];
    NSLog(@"UserName: ==== %@\n", userName);
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:2];
    [param setObject:@"getaccountinfo" forKey:@"action"];
    [param setObject:userName forKey:@"user_id"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestDetailFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    
}

- (void)iRequestDetailFinished:(NSData *)response
{
    [app hideProgressDialog];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    
    
    GDataXMLElement* rootElement = [doc rootElement];    
    NSLog(@"-----rootElement-----%@\n", rootElement);
    
    
    GDataXMLElement* headsElement = [[rootElement elementsForName:@"head"]objectAtIndex:0];
    NSLog(@"-----headsElement-----%@\n", headsElement);
    
    GDataXMLNode* returnCode = [[headsElement elementsForName:@"returncode"] objectAtIndex:0];
    NSInteger code = [[returnCode stringValue] intValue];
    if (code == -105){
        //        [AlertView showAlert:@"请先登录" action:@"goLogin"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录"
                                                       delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
        [alert show];
        [alert setTag:11];
        [alert release];
        return;
    } else if (code != 0 ){
        [AlertView showAlert:@"获取信息失败"];
    }
    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    
//    <msg><head><returncode>0</returncode><transcode>getaccountinfo</transcode></head><body><user_id>318813</user_id><score>135</score><account>0.0000</account><daijingquan>0.0000</daijingquan></body></msg>
    
    //某个具体节点的文本内容
    NSString* score = [[[bodyElement elementsForName:@"score"]objectAtIndex:0] stringValue];
    NSString* account = [[[bodyElement elementsForName:@"account"]objectAtIndex:0] stringValue];
    NSString* daijingquan = [[[bodyElement elementsForName:@"daijingquan"]objectAtIndex:0] stringValue];
    
    int count = textFields.count;
    for (int i = 0; i < count; i ++)
    {
        UITextField* tv = [textFields objectAtIndex:i];
        if (i == 0)
        {
            [tv setText:account];
        } else if (i == 1){
            [tv setText:daijingquan];
        } else if (i == 2){
            [tv setText:score];
        }

    }
    
    [doc release];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [keys release];
    [textFields release];
    [tableView release];
    
    [super dealloc];
}
- (void)viewWillAppear:(BOOL)animated
{
	[self.tableView deselectRowAtIndexPath:self.tableView.indexPathForSelectedRow animated:NO];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    detailModels = [[NSMutableArray alloc] init];
    
    app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍候"];
    [self.navigationItem setTitle:@"账户明细"];
    
    [self initView];
    [self search];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [detailModels count];
}

- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *kCellIdentifier = @"cellID";
	
	UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:kCellIdentifier];
	if (!cell)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kCellIdentifier] autorelease];
        
		cell.accessoryType = UITableViewCellAccessoryNone;
        
        cell.textLabel.backgroundColor = [UIColor clearColor];
		cell.textLabel.opaque = NO;
		cell.textLabel.textColor = [UIColor whiteColor];
		cell.textLabel.font = [UIFont boldSystemFontOfSize:13];
        [cell.textLabel setNumberOfLines:3];
    }
    
	// get the view controller's info dictionary based on the indexPath's row
	cell.textLabel.text = @"123123123123sdfsdf";
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {  
    NSLog(@"clickedButtonAtIndex:%d",buttonIndex);  
    
    if([alertView tag] == 11)
    {
        if (buttonIndex == 1)
        {
            LoginController* lc = [[LoginController alloc] init:self];
            [self.navigationController pushViewController:lc animated:YES];
            [lc release];
        }
    }
}  

@end
